import 'dart:async';

import 'package:enjoy_plus/utils/eventbus.dart';
import 'package:enjoy_plus/utils/http.dart';
import 'package:enjoy_plus/utils/toast.dart';
import 'package:enjoy_plus/utils/token.dart';
import 'package:flutter/material.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  // 1. 实现倒计时
  int _countdown = 60;
  bool _isCountingDown = false;
  Timer? _timer;

  //手机号输入框控制器
  final _phonecontroller = TextEditingController();

  //验证码输入框控制器
  final _codecontroller = TextEditingController();

  _submit() async {
    //校验手机号是否为空
    if (_phonecontroller.text.isEmpty) {
      return ToastUtil.showError('请输入手机号');
    }
    //校验手机号格式
    RegExp reg = RegExp(r'^1[0-9]{10}$');
    if (!reg.hasMatch(_phonecontroller.text)) {
      return ToastUtil.showError('手机号格式错误');
    }

    //校验验证码
    if (_codecontroller.text.isEmpty) {
      return ToastUtil.showError('请输入验证码');
    }
    //校验验证码格式
    if (!RegExp(r'^\d{6}$').hasMatch(_codecontroller.text)) {
      return ToastUtil.showError('验证码格式错误');
    }
    // 发送post请求
    final res = await http.post(
      '/login',
      data: {'mobile': _phonecontroller.text, 'code': _codecontroller.text},
    );
    //判断业务状态码是否异常
    if (res['code'] != 10000) {
      return ToastUtil.showError(res['message']);
    }
    //保存token到本地
    TokenManager().saveToken(res['data']['token']);
    //跳转
    Navigator.pop(context);
    //触发事件
    eventBus.fire(RefreshMine());
  }

  //获取验证码前，需校验手机号
  _getVerificationCode() async {
    //非空校验
    if (_phonecontroller.text.isEmpty) {
      return ToastUtil.showError('请输入手机号');
    }

    //正则表达式校验
    RegExp reg = RegExp(r'^1[0-9]{10}$');
    if (reg.hasMatch(_phonecontroller.text) == false) {
      return ToastUtil.showError('请输入正确的手机号');
    }

    final res = await http.get(
      '/code',
      queryParameters: {'mobile': _phonecontroller.text},
    );

    if (res['code'] != 10000) return ToastUtil.showError('获取验证码失败');
    ToastUtil.showSuccess('验证码已发送');

    Future.delayed(Duration(seconds: 2), () {
      _codecontroller.text = res['data']['code'];
    });

    _startCountdown();
  }

  void _startCountdown() {
    if (_isCountingDown) {
      return;
    }
    _isCountingDown = true;
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      setState(() {
        if (_countdown > 0) {
          _countdown--;
        } else {
          _isCountingDown = false;
          _countdown = 60;
          timer.cancel();
        }
      });
    });
  }

  @override
  void dispose() {
    super.dispose();
    // 取消定时器
    _timer?.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: const Text('登录'),
        backgroundColor: Colors.transparent,
        centerTitle: true,
      ),
      body: Container(
        padding: const EdgeInsets.all(20),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            const Row(
              children: [
                Text(
                  '登录',
                  style: TextStyle(fontSize: 25, fontWeight: FontWeight.bold),
                ),
              ],
            ),
            const SizedBox(height: 10),
            const Row(
              children: [Text('加入享+, 让生活更轻松', style: TextStyle(fontSize: 15))],
            ),
            const SizedBox(height: 30),
            Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Expanded(
                  child: TextField(
                    keyboardType: TextInputType.phone, // 限制键盘类型为手机号
                    maxLength: 11, //  限制输入长度为11
                    controller: _phonecontroller, //  绑定控制器
                    decoration: const InputDecoration(
                      labelText: '手机号',
                      hintText: '请输入手机号',
                    ),
                  ),
                ),
                ElevatedButton(
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.white,
                    shadowColor: Colors.transparent,
                    foregroundColor: const Color.fromARGB(255, 85, 145, 175),
                    minimumSize: const Size(100, 50),
                  ),
                  onPressed:
                      _isCountingDown
                          ? null //  禁用按钮
                          : () {
                            //先校验手机号，再获取验证码
                            _getVerificationCode();
                          },
                  child:
                      _isCountingDown
                          ? Text('$_countdown秒后获取')
                          : Text('获取验证码$_countdown'),
                ),
              ],
            ),
            const SizedBox(height: 8),
            TextField(
              keyboardType: TextInputType.number, // 限制键盘类型为手机号
              maxLength: 6, //  限制输入长度为11
              controller: _codecontroller, // 绑定控制器
              decoration: InputDecoration(
                labelText: '验证码',
                hintText: '请输入6位验证码',
              ),
            ),
            const SizedBox(height: 8),
            const Row(
              children: [
                Text(
                  '未注册手机号经验证后将自动登录',
                  style: TextStyle(fontSize: 12, color: Colors.grey),
                ),
              ],
            ),
            const SizedBox(height: 50),
            Row(
              children: [
                Expanded(
                  child: ElevatedButton(
                    style: ElevatedButton.styleFrom(
                      backgroundColor: const Color.fromARGB(255, 85, 145, 175),
                      minimumSize: const Size(100, 50),
                    ),
                    onPressed: () {
                      _submit();
                    },
                    child: const Text(
                      '登录',
                      style: TextStyle(color: Colors.white, fontSize: 20),
                    ),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
